package com.amat0urheu.controller.teacherController;


import com.alibaba.fastjson.JSONObject;
import com.amat0urheu.pojo.Case;
import com.amat0urheu.pojo.ReturnRes;
import com.amat0urheu.service.CaseService;
import com.amat0urheu.service.UploadFileService;
import com.amat0urheu.service.UploadService;
import com.amat0urheu.util.generator.SnowFlakeUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;


@RestController
@CrossOrigin
@RequestMapping("/api")
public class UploadFileController {
    /**
     * 服务对象
     */
    @Value("${marsctf.uploadPath}")
    private String uploadPath;

    @Value("${marsctf.imagePath}")
    private String imagePath;

    @Value("${marsctf.imageUrl}")
    private String imageUrl;

    @Resource
    private CaseService caseService;
    @Resource
    private UploadFileService uploadFileService;
    @Resource
    private UploadService uploadService;
    /**
     * 分页查询所有数据
     *
     * @return 所有数据
     */
    @PreAuthorize("hasRole('ROLE_admin')")
    @GetMapping("/admin/uploadFile/selectAll/{pageSize}/{pageNum}")
    ReturnRes selectAll(@PathVariable int pageSize,
                              @PathVariable int pageNum) {
        return uploadFileService.selectAllExperimentFile(pageSize, pageNum);
    }
//    @PreAuthorize("hasRole('ROLE_admin')")
    @GetMapping("/user/downloadFile/{fileId}")
    public ReturnRes downloadFile(@PathVariable String fileId, HttpServletResponse response) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        try {
            long startTime = System.currentTimeMillis();
            ReturnRes returnRes = uploadFileService.downloadFile(fileId, response);
            long endTime = System.currentTimeMillis();
            double elapsedTimeInSeconds = (endTime - startTime) / 1000.0;
            System.out.println("消耗时间: "+elapsedTimeInSeconds+"秒");

            return returnRes;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

        @PostMapping("/user/uploadExperimentFile")
        public ReturnRes uploadExperimentFiles(@RequestParam("file")MultipartFile file, @RequestParam("experimentName")String  experimentName , Authentication authentication) throws FileNotFoundException {
            try {
                if( uploadService.judgeTime(experimentName)){
                    return new ReturnRes(false, "实验已过期");
                }
                System.err.println("test");
                uploadService.uploadFileToExperiment(file,experimentName,authentication.getName());
                return new ReturnRes(true, "上传成功");
            }catch (Exception e){
                e.printStackTrace();
                return new ReturnRes(false, "上传失败，请来联系老师");
            }
        }

    @GetMapping("/admin/removeAllFiles")
    public ReturnRes removeAllFiles( )  {
        uploadService.removeAllFiles();
            return new ReturnRes(true, "删除完成");
    }



    @PostMapping("/admin/uploadUserFilesToServer")
    public ReturnRes uploadUserFilesToServer(@RequestParam("file")MultipartFile file, Authentication authentication) throws FileNotFoundException {
        try {
            return new ReturnRes(true, "上传成功");
        }catch (Exception e){
            e.printStackTrace();
            return new ReturnRes(false, "上传失败，请来联系老师");
        }
    }

    @PreAuthorize("hasRole('ROLE_admin')")
    @GetMapping("/admin/downloadAllExperiments")
    public ResponseEntity<byte[]> downloadAllExperiments() {

        return uploadFileService.downLoadExperimentFiles();
    }

    @PostMapping("/admin/casePictureUpload")
    public ReturnRes handleFileUpload(@RequestParam("casePicture") MultipartFile file,@RequestParam(name = "data") String caseJson) {
        if (file.isEmpty()) {
            return new ReturnRes(false, "上传文件不能为空");
        }

        try {
            Case acase = JSONObject.parseObject(caseJson, Case.class);
            String fileName = file.getOriginalFilename();
            int lastIndexOf = fileName.lastIndexOf(".");
            String ext = lastIndexOf != -1 ? fileName.substring(lastIndexOf + 1) : "";
            String newName = String.valueOf(SnowFlakeUtil.generatorUid()) + "." + ext;
            System.out.println(imageUrl+newName);
            File dest = new File(imagePath + imageUrl, newName);

            acase.setCasePicture(imageUrl+newName);
            file.transferTo(dest);
            return caseService.saveCase(acase);
        } catch (Exception e) {
            return new ReturnRes(false, "添加失败");
        }
    }



}
